package com.nandi.deviceinstall.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.GridLayoutManager
import com.afollestad.materialdialogs.DialogAction
import com.afollestad.materialdialogs.MaterialDialog
import com.esri.arcgisruntime.ArcGISRuntimeEnvironment
import com.esri.arcgisruntime.geometry.Point
import com.esri.arcgisruntime.geometry.SpatialReferences
import com.esri.arcgisruntime.mapping.ArcGISMap
import com.esri.arcgisruntime.mapping.Basemap
import com.esri.arcgisruntime.mapping.Viewpoint
import com.esri.arcgisruntime.mapping.view.Graphic
import com.esri.arcgisruntime.mapping.view.GraphicsOverlay
import com.esri.arcgisruntime.mapping.view.LocationDisplay
import com.esri.arcgisruntime.symbology.SimpleMarkerSymbol
import com.jaygoo.selector.MultiSelectPopWindow
import com.lzy.imagepicker.ImagePicker
import com.lzy.imagepicker.bean.ImageItem
import com.lzy.imagepicker.ui.ImageGridActivity
import com.nandi.deviceinstall.R
import com.nandi.deviceinstall.base.BaseMvpActivity
import com.nandi.deviceinstall.bean.*
import com.nandi.deviceinstall.common.Constant
import com.nandi.deviceinstall.contract.EquipmentBindContract
import com.nandi.deviceinstall.net.dto.BindAddDTO
import com.nandi.deviceinstall.net.dto.BindUpdateDTO
import com.nandi.deviceinstall.presenter.EquipmentBindPresenter
import com.nandi.deviceinstall.util.CustomToast
import com.nandi.deviceinstall.util.SharedTool
import com.nandi.deviceinstall.util.SxTransformUtils
import com.nandi.deviceinstall.weight.InitDataListener
import com.nandi.deviceinstall.weight.imagepicker.*
import com.uuzuche.lib_zxing.activity.CaptureActivity
import com.uuzuche.lib_zxing.activity.CodeUtils
import kotlinx.android.synthetic.main.activity_equipment_binding.*
import kotlinx.android.synthetic.main.activity_equipment_binding.deviceFac
import kotlinx.android.synthetic.main.activity_equipment_binding.deviceNum
import kotlinx.android.synthetic.main.activity_equipment_binding.deviceType
import kotlinx.android.synthetic.main.activity_equipment_binding.disasterName
import kotlinx.android.synthetic.main.activity_equipment_binding.disasterNum
import kotlinx.android.synthetic.main.activity_equipment_binding.district
import kotlinx.android.synthetic.main.activity_equipment_binding.img_show
import kotlinx.android.synthetic.main.activity_equipment_binding.location
import kotlinx.android.synthetic.main.activity_equipment_binding.mapView
import kotlinx.android.synthetic.main.activity_equipment_binding.monitorNum
import kotlinx.android.synthetic.main.activity_equipment_binding.township
import kotlinx.android.synthetic.main.activity_equipment_step.*
import kotlinx.android.synthetic.main.dialog_tips.view.*
import kotlinx.android.synthetic.main.layout_binding_info.view.*

import kotlinx.android.synthetic.main.toolbar_back_include.*
import java.io.File
import java.util.ArrayList

class EquipmentBindingActivity : BaseMvpActivity<EquipmentBindPresenter>(), EquipmentBindContract.View {


    private lateinit var mLocationDisplay: LocationDisplay
    private lateinit var adapter: ImagePickerAdapter
    private val maxImgCount = 10000 // 最大选择图片数量
    internal var selImageList: MutableList<ImageItem> = ArrayList() //图片集合
    internal var deleteImageList: MutableList<ImageItem> = ArrayList() //删除图片集合
    private lateinit var dialog: AlertDialog
    private val listDeviceType = arrayOf("地裂缝", "墙裂缝", "地面倾斜", "智能报警器", "雨量计", "泥位计")
    private var listCitys: MutableList<CityBean.DataBean> = mutableListOf()
    private var listTowns: MutableList<TownBean.DataBean> = mutableListOf()
    private var listFactorys: MutableList<DeviceFacBean.DataBean> = mutableListOf()
    private var listMonitorNums: MutableList<ListMonitorNumBean.DataBean> = mutableListOf()
    private lateinit var cityAdapter: ArrayAdapter<String>
    private lateinit var townAdapter: ArrayAdapter<String>
    private lateinit var disasterNameAdapter: ArrayAdapter<String>
    private lateinit var disasterNuAdapter: ArrayAdapter<String>
    private lateinit var monitorNumAdapter: ArrayAdapter<String>
    private lateinit var deviceFacsAdapter: ArrayAdapter<String>
    private lateinit var typesAdapter: ArrayAdapter<String>
    private lateinit var action: String
    private val monitorNuUuidBuffer = StringBuffer()
    private var token = ""
    private lateinit var bindInfo: BindRecordBean.DataBean.RecordsBean
    private var isChoice = false
    private var isLocation = false
    private var isSelectCity = false
    private var isSelectTown = false
    private var isFirstUpdate = false
    private var mGraphicsOverlay: GraphicsOverlay = GraphicsOverlay()
    private var disasterNameloc: String = ""
    override val layoutId: Int
        get() = R.layout.activity_equipment_binding

    override fun initView() {
        token = SharedTool.get(context, Constant.TOKEN, "") as String
        mPresenter = EquipmentBindPresenter()
        mPresenter.attachView(this)

        action = intent.extras.getString("action")
        initListener()
        initImagePicker()
        setupMap()
        mPresenter.requestListCity(SharedTool.get(context, Constant.TOKEN, "") as String, "")
        if ("add" == action) {
            iv_back_toolbar.visibility = View.GONE
            tv_title_toolbar.text = "设备安装绑点"
            title_image.setImageResource(R.drawable.record)
            setupLocationDisplay()
        } else if ("update" == action) {
            bindInfo = intent.extras.getSerializable("bindInfo") as BindRecordBean.DataBean.RecordsBean
            tv_title_toolbar.text = "绑点信息修改"
            ll_right.visibility = View.GONE
            initData()
        }
    }

    private fun setupMap() {
        if (mapView != null) {
            ArcGISRuntimeEnvironment.setLicense("runtimelite,1000,rud6849747514,none,0JMFA0PL4S2HLMZ59106")
            mapView.isAttributionTextVisible = false
            val basemapType = Basemap.Type.IMAGERY
            val latitude = 29.09042

            val longitude = 106.71511
            val levelOfDetail = 11
            val map = ArcGISMap(basemapType, latitude, longitude, levelOfDetail)
            mapView.map = map
        }
    }

    private fun setupLocationDisplay() {
        mLocationDisplay = mapView.locationDisplay
        mLocationDisplay.autoPanMode = LocationDisplay.AutoPanMode.COMPASS_NAVIGATION
        mLocationDisplay.addLocationChangedListener { p0 ->
            if (!isLocation) {
                val x = p0?.location?.position?.x
                val y = p0?.location?.position?.y
                lon_bind_1.text = x.toString()
                lat_bind_1.text = y.toString()
                if (x != null && y != null) {
                    val locationAddress = SxTransformUtils.getLocationAddress(context, x, y)
                    district.text = locationAddress
                    district.setTextColor(Color.BLACK)
                    district.textSize = 18f
                    isLocation = true
                }
            }
        }
        mLocationDisplay.startAsync()
    }

    private fun initData() {
        isChoice = false
        isFirstUpdate = true
        //mPresenter.requestListCity(SharedTool.get(context, Constant.TOKEN, "") as String, "")

        deviceType.text = listDeviceType[bindInfo.devType]
        deviceType.setTextColor(Color.BLACK)
        deviceType.textSize = 18f

        district.text = bindInfo.cityName
        district.setTextColor(Color.BLACK)
        district.textSize = 18f

        township.text = bindInfo.townName
        township.setTextColor(Color.BLACK)
        township.textSize = 18f

        disasterName.setText(bindInfo.disasterName)
        disasterName.setTextColor(Color.BLACK)
        disasterName.textSize = 18f

        disasterNum.text = bindInfo.disNo
        disasterNum.setTextColor(Color.BLACK)
        disasterNum.textSize = 18f

        monitorNum.text = bindInfo.monitorNo
        monitorNum.setTextColor(Color.BLACK)
        monitorNum.textSize = 18f

        deviceFac.setText(bindInfo.devFactory)
        deviceFac.setTextColor(Color.BLACK)
        deviceFac.textSize = 18f

        deviceNum.setText(bindInfo.devName)
        deviceNum.setTextColor(Color.BLACK)
        deviceNum.textSize = 18f

        lon_bind_1.text = bindInfo.installLongitude

        lat_bind_1.text = bindInfo.installLatitude

        installLoc.setText(bindInfo.installLocation)
        installLoc.setTextColor(Color.BLACK)
        installLoc.textSize = 18f
        val split = bindInfo.devImage?.split(",")
        selImageList.clear()
        split?.forEach {
            if (it.isNotEmpty()) {
                val imageItem = ImageItem()
                imageItem.name = it.substring(it.lastIndexOf("/") + 1)
                imageItem.path = "${Constant.fileUrl}${it}&type=3"
                imageItem.mimeType = it
                selImageList.add(imageItem)
            }
        }
        setLocationPointOverlay(bindInfo.installLongitude.toDouble(), bindInfo.installLatitude.toDouble())
        adapter.images = selImageList
        isFirstUpdate = false
    }

    private fun initListener() {
        ll_right.setOnClickListener {
            startActivity(Intent(context, RecordActivity::class.java))
        }

        location.setOnClickListener {
            if ("update" == action) {
                setupLocationDisplay()
            } else {
                val v = Viewpoint(lat_bind_1.text.toString().toDouble(),
                        lon_bind_1.text.toString().toDouble(), mapView.mapScale)
                mapView.setViewpointAsync(v, 2f)
            }
        }
        iv_back_toolbar.setOnClickListener {
            var content = ""
            if ("add" == action) {
                content = "返回后将清空已填内容,确认返回？"
            } else if ("update" == action) {
                content = "修改内容不会被保存,确认返回？"
            }
            MaterialDialog.Builder(this)
                    .title("提示")
                    .content(content)
                    .positiveText("确认")
                    .negativeText("取消")
                    .onPositive(object : MaterialDialog.SingleButtonCallback {
                        override fun onClick(dialog: MaterialDialog, which: DialogAction) {
                            finish()
                        }
                    })
                    .show()
        }
        //上传
        upload_equipment_binding.setOnClickListener {

            if (checkInfo()) return@setOnClickListener

            initDialog()
        }

        //设备类型下拉选择
        typesAdapter = ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, listDeviceType)
        deviceType.setAdapter(typesAdapter)
        deviceType.setInitDataListener {
            deviceType.showPopWindow()
        }

        district.setInitDataListener(object : InitDataListener {
            override fun initData() {
                if (listCitys.isEmpty()) {
                    return
                }
                district.showPopWindow()
            }
        })
        district.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (district.isTextChanged) {
                    isSelectCity = true
                    township.text = ""
                    disasterName.setText("")
                    disasterNum.text = ""
                    monitorNum.text = ""
                    isSelectCity = false
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })

        township.setInitDataListener(object : InitDataListener {
            override fun initData() {
                if (district.text.isNotEmpty()) {
                    if ("update" == action && district.getmPosition() == -1) {
                        mPresenter.requestListTown(token, bindInfo.city)
                    } else {
                        val indexOf = citys.indexOf(district.text.toString())
                        if (indexOf == -1) {
                            showLongToast("请输入正确的区县名称!")
                            initTipsDialog("请输入或选择区县")
                            return
                        }
                        val id = if (district.getmPosition() == -1) {
                            listCitys[indexOf].id
                        } else {
                            listCitys[district.getmPosition()].id
                        }
                        mPresenter.requestListTown(token, id!!)
                    }
                } else {
                    showLongToast("请先选择区县!")
                }
            }

        })

        township.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (township.isTextChanged) {
                    isSelectTown = true
                    disasterName.setText("")
                    disasterNum.text = ""
                    monitorNum.text = ""
                    isSelectTown = false
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })


        disasterName.setInitDataListener(object : InitDataListener {
            override fun initData() {
                if (township.text.isNotEmpty()) {
                    if ("update" == action && township.getmPosition() == -1) {
                        mPresenter.requestListDisaster(token, bindInfo.townCode!!)
                    } else {
                        val areaCode = listTowns[township.getmPosition()].areaCode
                        mPresenter.requestListDisaster(token, areaCode!!)
                    }
                } else {
                    showLongToast("请先选择乡镇!")
                }
            }

        })

        disasterName.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (p0.toString() != disasterNameloc) {
                    disasterNum.text = ""
                    monitorNum.text = ""
                }

                if (!disasterName.isMySelected && !isSelectCity && !isSelectTown && !isFirstUpdate) {
                    if (district.text.isEmpty()) {
                        CustomToast.showToast(context, "请选择区县")
                        return
                    }
                    if (township.text.isEmpty()) {
                        CustomToast.showToast(context, "请选择乡镇")
                        return
                    }
                    if (p0.toString().isEmpty()) {
                        return
                    }
                    if ("update" == action && township.getmPosition() == -1) {
                        mPresenter.requestDisName(token, p0.toString(), bindInfo.townCode!!)
                    } else {
                        mPresenter.requestDisName(token, p0.toString(), listTowns[township.getmPosition()].areaCode!!)
                    }
                }
                disasterNameloc = p0.toString()
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

        })

        disasterNum.setInitDataListener(object : InitDataListener {
            override fun initData() {
                if (disasterName.text.isNotEmpty()) {
                    if ("update" == action && township.getmPosition() == -1) {
                        mPresenter.requestDisNum(token, disasterName.text.toString(), bindInfo.townCode!!)
                    } else {
                        val areaCode = listTowns[township.getmPosition()].areaCode
                        mPresenter.requestDisNum(token, disasterName.text.toString(), areaCode!!)
                    }
                } else {
                    showLongToast("请先选择或填写灾害点名称!")
                }
            }

        })

        disasterNum.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (disasterNum.isTextChanged) {
                    monitorNum.text = ""
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }
        })

        monitorNum.setInitDataListener(object : InitDataListener {
            override fun initData() {
                if (disasterNum.text.isNotEmpty()) {
                    mPresenter.requestListMonitorNum(SharedTool.get(context, Constant.TOKEN, "") as String,
                            disasterNum.text.toString())
                } else {
                    showLongToast("请选择灾害点编号!")
                }
            }
        })

        deviceFac.setInitDataListener(object : InitDataListener {
            override fun initData() {
                mPresenter.requestListDevFactory(SharedTool.get(context, Constant.TOKEN, "") as String, "")
            }
        })

        deviceFac.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {
                if (!deviceFac.isMySelected && !isFirstUpdate) {
                    if (p0.toString().isEmpty()) {
                        return
                    }
                    mPresenter.requestListDevFactory(token, p0.toString())
                }
            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }
        })

        scan.setOnClickListener {
            val intent = Intent(context, CaptureActivity::class.java)
            startActivityForResult(intent, Constant.ZXING_REQUEST_CODE)
        }

        tv_monitor_pic.setOnClickListener {
            val path: String
            if (monitorNum.text.isEmpty()) {
                CustomToast.showToast(context, "请先选择监测点编号!")
                return@setOnClickListener
            }
            if ("update" == action) {
                if (monitorNum.getmPosition() == -1) {
                    path = "${Constant.fileUrl}${bindInfo.pointPic}&type=3"
                } else {
                    path = "${Constant.fileUrl}${listMonitorNums[monitorNum.getmPosition()].pointPic!!}&type=3"
                }
            } else {
                path = "${Constant.fileUrl}${listMonitorNums.get(monitorNum.getmPosition()).pointPic!!}&type=3"
            }
            if (path.isNotEmpty()) {
                val intent = Intent(this@EquipmentBindingActivity, MonitorPicActivity::class.java)
                intent.putExtra("path", path)
                startActivity(intent)
            }
        }
    }

    private fun checkInfo(): Boolean {
        if (deviceType.text.toString().isEmpty()) {
            initTipsDialog("请选择设备类型")
            return true
        }

        if (district.text.toString().isEmpty()) {
            initTipsDialog("请选择区县")
            return true
        }

        if (township.text.toString().isEmpty()) {
            initTipsDialog("请选择乡镇")
            return true
        }

        if (disasterName.text.toString().isNotEmpty()) {
            if (disasterNum.text.toString().isEmpty()) {
                initTipsDialog("请选择灾害点编号")
                return true
            }

            if (monitorNum.text.toString().isEmpty()) {
                initTipsDialog("请选择监测点编号")
                return true
            }
        }


        if (deviceNum.text.toString().isEmpty()) {
            initTipsDialog("请输入设备编号")
            return true
        }
        if (lat_bind_1.text.toString() == "0.0") {
            initTipsDialog("请等待经纬度获取")
            return true
        }
        return false
    }

    private var citys = mutableListOf<String>()

    override fun handlerListCityResult(result: CityBean) {
        listCitys.clear()
        listCitys.addAll(result.data!!)
        citys.clear()
        result.data?.forEach {
            citys.add(it.areaName!!)
        }
        cityAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, citys)
        district.setAdapter(cityAdapter)
        //district.showPopWindow()
    }

    private var towns = mutableListOf<String>()

    override fun handlerListTownResult(result: TownBean) {
        listTowns.clear()
        listTowns.addAll(result.data!!)
        towns.clear()
        result.data?.forEach {
            towns.add(it.areaName!!)
        }
        townAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, towns)
        township.setAdapter(townAdapter)
        township.showPopWindow()
    }

    override fun handlerListDisasterResult(result: DisasterBean) {

        if (result.data!!.isNotEmpty()) {
            var disastersName = mutableListOf<String>()
            result.data?.forEach {
                disastersName.add(it.disasterName!!)
            }
            disasterNameAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, disastersName)
            disasterName.setAdapter(disasterNameAdapter)
            disasterName.showPopWindow()
        } else {
            showShortToast("没有相关灾害点!")
        }
    }

    override fun handlerDisNum(result: DisNumBean) {
        if (result.data!!.isNotEmpty()) {
            var disastersNu = mutableListOf<String>()
            result.data?.forEach {
                disastersNu.add(it)
            }
            disasterNuAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, disastersNu)
            disasterNum.setAdapter(disasterNuAdapter)
            disasterNum.showPopWindow()
        } else {
            showShortToast("没有相关灾害点编号!")
        }

    }

    override fun handlerMonitorNum(result: ListMonitorNumBean) {

        if (result.data != null) {
            listMonitorNums.clear()
            listMonitorNums.addAll(result.data!!)
            val monitorNums = mutableListOf<String>()
            result.data?.forEach {
                monitorNums.add(it.monitorNo!!)
            }
            if (deviceType.text.toString() == "智能报警器") {
                isChoice = true
                MultiSelectPopWindow.Builder(this)
                        .setNameArray(monitorNums as ArrayList<String>)
                        .setConfirmListener { indexList, selectedList ->
                            val monitorNuBuffer = StringBuffer()
                            for (i in indexList) {
                                /*monitorNuBuffer.append(selectedList[i])
                                monitorNuBuffer.append(",")*/
                                monitorNuUuidBuffer.append(result.data!![i].uuid)
                                monitorNuUuidBuffer.append(",")
                            }
                            selectedList.forEach {
                                monitorNuBuffer.append(it)
                                monitorNuBuffer.append(",")
                            }
                            monitorNum.text = monitorNuBuffer.substring(0, monitorNuBuffer.length - 1)
                            monitorNum.setTextColor(Color.BLACK)
                            monitorNum.textSize = 18f
                        }
                        .setCancel("取消")
                        .setConfirm("完成")
                        .setTitle("编号列表")
                        .build()
                        .show(findViewById(R.id.mBottom))
            } else {
                monitorNumAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, monitorNums)
                monitorNum.setAdapter(monitorNumAdapter)
                monitorNum.showPopWindow()
            }
        } else {
            showLongToast("此灾害点没有监测点编号!")
        }
    }

    override fun handlerDevFactory(result: DeviceFacBean) {
        if (result.data!!.isNotEmpty()) {
            listFactorys.clear()
            listFactorys.addAll(result.data!!)
            val deviceFacs = mutableListOf<String>()
            result.data?.forEach {
                deviceFacs.add(it.factory!!)
            }
            deviceFacsAdapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, deviceFacs)
            deviceFac.setAdapter(deviceFacsAdapter)
            deviceFac.showPopWindow()
        }
    }

    override fun handlerAddBindResult(result: BaseObjectBean<BindAddBean>) {
        if (result.code == 0) {
            val intent = Intent(context, BindingSuccessActivity::class.java)
            intent.putExtra("id", result.data!!.id)
            startActivity(intent)
            finish()
        } else {
            CustomToast.showToast(context, result.msg)
        }
    }

    override fun handlerUpdateBindResult(result: BaseObjectBean<BindAddBean>) {
        if (result.code == 0) {
            val intent = Intent(context, BindingSuccessActivity::class.java)
            intent.putExtra("id", result.data!!.id)
            startActivity(intent)
            finish()
        } else {
            CustomToast.showToast(context, result.msg)
        }
    }

    override fun handlerDisNameResult(result: DisNameBean) {
        if (result.data!!.records!!.isNotEmpty()) {
            var disastersName = mutableListOf<String>()
            result.data?.records?.forEach {
                disastersName.add(it.disasterName!!)
            }
            disasterNameAdapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, disastersName)
            disasterName.setAdapter(disasterNameAdapter)
            disasterName.showPopWindow()
        } /*else {
            showShortToast("没有相关灾害点!")
        }*/
    }

    override fun uploadPicSuccess(result: UploadPicBean) {
        if (result.data.isNotEmpty()) {
            var imageItem = ImageItem()
            imageItem.name = result.data.substring(result.data.lastIndexOf("/") + 1)

            imageItem.path = "${Constant.fileUrl}${result.data}&type=3"
            imageItem.mimeType = result.data
            selImageList.add(imageItem)
            adapter.images = selImageList
        }
    }

    override fun removeDevPicFile(result: DevPicRemoveBean) {
        selImageList.removeAll(deleteImageList)
        adapter.images = selImageList
    }

    private fun initDialog() {
        val dialogView = View.inflate(this, R.layout.layout_binding_info, null)

        dialogView.deviceType.text = "${deviceType.text}"
        dialogView.address.text = "${district.text}${township.text}"
        dialogView.disasterName.text = "${disasterName.text}"
        dialogView.disasterNum.text = "${disasterNum.text}"
        dialogView.monitorNum.text = "${monitorNum.text}"
        dialogView.deviceFac.text = "${deviceFac.text}"
        dialogView.deviceNum.text = "${deviceNum.text}"
        dialogView.cunzu.text = "${installLoc.text}"
        dialogView.cancelss.setOnClickListener { dialog.dismiss() }

        dialogView.back.setOnClickListener {
            dialog.dismiss()
        }
        dialogView.upload.setOnClickListener {
            if ("add" == action) {
                val bindAddDTO = BindAddDTO()
                bindAddDTO.devType = deviceType.getmPosition()
//                bindAddDTO.factoryId = listFactorys[deviceFac.getmPosition()].id
//                bindAddDTO.devFactory = deviceFac.text.toString()
                bindAddDTO.installLatitude = lat_bind_1.text.toString()
                bindAddDTO.installLongitude = lon_bind_1.text.toString()
                bindAddDTO.installLocation = installLoc.text.toString()
                if (selImageList.size > 0) {
                    val picStringBuffer = StringBuffer()
                    for (imageItem in selImageList) {
                        picStringBuffer.append(imageItem.mimeType)
                        picStringBuffer.append(",")
                    }
                    bindAddDTO.devImage = picStringBuffer.substring(0, picStringBuffer.length - 1)
                } else {
                    bindAddDTO.devImage = ""
                }
                bindAddDTO.areaCode = listTowns[township.getmPosition()].areaCode!!
                bindAddDTO.disNo = disasterNum.text.toString()
                if (monitorNum.getmPosition() !=-1){
                    if (deviceType.text.toString() == "智能报警器") {
                        bindAddDTO.uuid = monitorNuUuidBuffer.substring(0, monitorNuUuidBuffer.length - 1)
                    } else {
                        bindAddDTO.uuid = listMonitorNums[monitorNum.getmPosition()].uuid!!
                    }
                }
                bindAddDTO.devName = deviceNum.text.toString()
                mPresenter.requestAddBind(token, bindAddDTO)
            } else if ("update" == action) {
                val bindUpdateDTO = BindUpdateDTO()
                if (deviceType.getmPosition() == -1) {
                    bindUpdateDTO.devType = bindInfo.devType
                } else {
                    bindUpdateDTO.devType = deviceType.getmPosition()
                }
//                if (deviceFac.getmPosition() == -1) {
//                    bindUpdateDTO.factoryId = bindInfo.factoryId as Int
//                } else {
//                    bindUpdateDTO.factoryId = listFactorys[deviceFac.getmPosition()].id
//                }
                bindUpdateDTO.installLatitude = lat_bind_1.text.toString()
                bindUpdateDTO.installLongitude = lon_bind_1.text.toString()
                bindUpdateDTO.installLocation = installLoc.text.toString()
                bindUpdateDTO.devFactory = deviceFac.text.toString()
                if (selImageList.size > 0) {
                    val picStringBuffer = StringBuffer()
                    for (imageItem in selImageList) {
                        picStringBuffer.append(imageItem.mimeType)
                        picStringBuffer.append(",")
                    }
                    bindUpdateDTO.devImage = picStringBuffer.substring(0, picStringBuffer.length - 1)
                } else {
                    bindUpdateDTO.devImage = ""
                }
                if (township.getmPosition() == -1) {
                    bindUpdateDTO.areaCode = bindInfo.townCode!!
                } else {
                    bindUpdateDTO.areaCode = listTowns[township.getmPosition()].areaCode!!
                }
                bindUpdateDTO.disNo = disasterNum.text.toString()
                if (deviceType.text.toString() == "智能报警器") {
                    if (isChoice) {
                        bindUpdateDTO.uuid = monitorNuUuidBuffer.substring(0, monitorNuUuidBuffer.length - 1)
                    } else {
                        bindUpdateDTO.uuid = bindInfo.uuid!!
                    }
                } else {
                    if (monitorNum.getmPosition() == -1) {
                        bindUpdateDTO.uuid = bindInfo.uuid!!
                    } else {
                        bindUpdateDTO.uuid = listMonitorNums[monitorNum.getmPosition()].uuid!!
                    }
                }
                bindUpdateDTO.devName = deviceNum.text.toString()
                bindUpdateDTO.id = bindInfo.id
                mPresenter.requestUpdateBind(token, bindUpdateDTO)
            }
            dialog.dismiss()

            //startActivity(Intent(context, BindingSuccessActivity::class.java))
        }
        dialog = AlertDialog.Builder(this).setView(dialogView).create()
        dialog.show()
    }

    override fun showLoading() {
    }

    override fun hideLoading() {
    }

    override fun onError(msg: String, code: Int) {
        CustomToast.showToast(context, msg)
    }

    /**
     * 初始化图片选择器
     */
    private fun initImagePicker() {
        val imagePicker = ImagePicker.getInstance()
        //设置图片加载器
        imagePicker.imageLoader = GlideImageLoader()
        //显示拍照按钮
        imagePicker.isShowCamera = true
        //允许裁剪（单选才有效）
        imagePicker.isCrop = false
        //是否按矩形区域保存
        imagePicker.isSaveRectangle = true
        //选中数量限制
        imagePicker.selectLimit = maxImgCount
        //多选
        imagePicker.isMultiMode = true

        adapter = ImagePickerAdapter(this, selImageList, maxImgCount)
        adapter.setOnItemClickListener(object : ImagePickerAdapter.OnRecyclerViewItemClickListener {
            override fun onItemClick(view: View?, position: Int) {
                when (position) {
                    IMAGE_ITEM_ADD -> {
                        ImagePicker.getInstance().selectLimit = maxImgCount - selImageList.size
                        val intent1 = Intent(context, ImageGridActivity::class.java)
                        startActivityForResult(intent1, REQ_CODE_SELECT)//打开选择,本次允许选择的数量
                    }
                    else -> {
                        //打开预览
                        val intentPreview = Intent(context, ImagePreviewDelActivity::class.java)
                        intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, adapter.getImages() as ArrayList<ImageItem>)
                        intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position)
                        intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true)
                        startActivityForResult(intentPreview, REQ_CODE_PREVIEW)
                    }

                }
            }
        })
        img_show.layoutManager = GridLayoutManager(this, 3)
        img_show.setHasFixedSize(true)
        img_show.adapter = adapter
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQ_CODE_SELECT) {
                val images = data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS) as ArrayList<ImageItem>
                mPresenter.requestUploadDevPic(SharedTool.get(context, Constant.TOKEN, "") as String, File(images[0].path))
                //selImageList.addAll(images)
                //adapter.images = selImageList
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQ_CODE_PREVIEW) {
                val images = data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS) as ArrayList<ImageItem>
                //selImageList.clear()
                //selImageList.addAll(images)
                //adapter.images = selImageList
                deleteImageList.clear()
                deleteImageList.addAll(selImageList)
                deleteImageList.removeAll(images)
                if (deleteImageList.size > 0) {
                    mPresenter.requestRemoveDevPicFile(token, deleteImageList[0].mimeType)
                }
            }
        } else if (requestCode == Constant.ZXING_REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                var bundle: Bundle? = data.extras ?: return
                if (bundle!!.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    var result = bundle!!.getString(CodeUtils.RESULT_STRING)
                    deviceNum.setText(result)
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(context, "解析二维码失败", Toast.LENGTH_LONG).show()
                }
            }
        }
    }

    override fun onBackPressed() {
        var content = ""
        if ("add" == action) {
            content = "返回后将清空已填内容,确认返回？"
        } else if ("update" == action) {
            content = "修改内容不会被保存,确认返回？"
        }
        MaterialDialog.Builder(this)
                .title("提示")
                .content(content)
                .positiveText("确认")
                .negativeText("取消")
                .onPositive(object : MaterialDialog.SingleButtonCallback {
                    override fun onClick(dialog: MaterialDialog, which: DialogAction) {
                        finish()
                    }
                })
                .show()
    }

    @SuppressLint("SetTextI18n", "InflateParams")
    private fun initTipsDialog(s: String) {
        val inflate = LayoutInflater.from(context).inflate(R.layout.dialog_tips, null)
        inflate.tips.text = "温馨提示"
        inflate.content.text = s
        val show = android.app.AlertDialog.Builder(context)
                .setView(inflate)
                .setCancelable(false)
                .show()
        inflate.cancels.setOnClickListener {
            show.dismiss()
        }
    }

    private fun setLocationPointOverlay(long: Double, latu: Double) {
        lon_bind_1.text = long.toString()

        lat_bind_1.text = latu.toString()
        val simpleMarkerSymbol = SimpleMarkerSymbol(SimpleMarkerSymbol.Style.CIRCLE, Color.RED, 20F)

        val point = Point(long, latu, SpatialReferences.getWgs84())
        val graphic = Graphic(point, simpleMarkerSymbol)
        graphic.zIndex = 0x110
        mGraphicsOverlay.graphics.add(graphic)
        mapView.graphicsOverlays.add(mGraphicsOverlay)
        val v = Viewpoint(latu, long, 10000.toDouble())
        mapView.setViewpointAsync(v, 2F)

    }

}

